package com.zhentao.controller;

import cn.hutool.core.bean.BeanUtil;
import com.zhentao.dto.CouponDTO;
import com.zhentao.dto.ReceiveCouponDTO;
import com.zhentao.dto.UserCouponDTO;
import com.zhentao.dto.UserDTO;
import com.zhentao.service.CouponService;
import com.zhentao.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 优惠券Controller
 */
@Slf4j
@RestController
@RequestMapping("/coupon")
@CrossOrigin
public class CouponController {
    
    @Autowired
    private CouponService couponService;
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    /**
     * 获取可领取的优惠券列表
     */
    @GetMapping("/available")
    public Result getAvailableCoupons() {
        try {
            List<CouponDTO> coupons = couponService.getAvailableCoupons();
            return Result.ok(coupons);
        } catch (Exception e) {
            log.error("获取可领取优惠券失败", e);
            return Result.fail("获取优惠券失败");
        }
    }
    
    /**
     * 用户领取优惠券
     */
    @PostMapping("/receive")
    public Result receiveCoupon(@RequestBody ReceiveCouponDTO receiveCouponDTO, 
                               @RequestHeader("Authorization") String token) {
        try {
            // 从token获取用户ID
            Long userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.fail("用户未登录");
            }
            
            boolean success = couponService.receiveCoupon(userId, receiveCouponDTO.getCouponId());
            if (success) {
                return Result.ok("领取成功");
            } else {
                return Result.fail("领取失败，请检查优惠券是否可用");
            }
        } catch (Exception e) {
            log.error("领取优惠券失败", e);
            return Result.fail("领取失败");
        }
    }
    
    /**
     * 获取用户已领取的优惠券列表
     */
    @GetMapping("/my")
    public Result getUserCoupons(@RequestHeader("Authorization") String token) {
        try {
            Long userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.fail("用户未登录");
            }
            
            List<UserCouponDTO> userCoupons = couponService.getUserCoupons(userId);
            return Result.ok(userCoupons);
        } catch (Exception e) {
            log.error("获取用户优惠券失败", e);
            return Result.fail("获取优惠券失败");
        }
    }
    
    /**
     * 获取用户可用的优惠券列表
     */
    @GetMapping("/my/available")
    public Result getUserAvailableCoupons(@RequestHeader("Authorization") String token) {
        try {
            Long userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.fail("用户未登录");
            }
            
            List<UserCouponDTO> userCoupons = couponService.getUserAvailableCoupons(userId);
            return Result.ok(userCoupons);
        } catch (Exception e) {
            log.error("获取用户可用优惠券失败", e);
            return Result.fail("获取优惠券失败");
        }
    }
    
    /**
     * 使用优惠券
     */
    @PostMapping("/use")
    public Result useCoupon(@RequestParam Long userCouponId, 
                           @RequestParam Long orderId,
                           @RequestHeader("Authorization") String token) {
        try {
            Long userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.fail("用户未登录");
            }
            
            boolean success = couponService.useCoupon(userId, userCouponId, orderId);
            if (success) {
                return Result.ok("使用成功");
            } else {
                return Result.fail("使用失败，请检查优惠券状态");
            }
        } catch (Exception e) {
            log.error("使用优惠券失败", e);
            return Result.fail("使用失败");
        }
    }
    
    /**
     * 从token获取用户ID
     */
    private Long getUserIdFromToken(String token) {
        try {
            // 从Redis中根据token获取用户信息
            String tokenKey = "login:user:" + token;
            Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
            
            if (userMap == null || userMap.isEmpty()) {
                log.warn("token无效或已过期: {}", token);
                return null;
            }
            
            // 获取用户ID
            Object userIdObj = userMap.get("id");
            if (userIdObj == null) {
                log.warn("用户信息中缺少ID字段: {}", userMap);
                return null;
            }
            
            return Long.valueOf(userIdObj.toString());
        } catch (Exception e) {
            log.error("解析token失败: {}", token, e);
            return null;
        }
    }
} 